package com.alex.megacj.scenario;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.io.Resource;

import com.alex.megacj.handler.RequestContext;
import com.alex.megacj.mapper.URLMapper;

public class CommonScenario extends Scenario {

	private URLMapper urlMapper;

	private Set<String> hosts;

	public void setHostsResource(Resource hostsResource) throws IOException {
		InputStream in = null;
		try {
			in = hostsResource.getInputStream();
			String str = IOUtils.toString(in);
			hosts = new HashSet<String>(Arrays.asList(StringUtils.split(str, "\n")));
		} finally {
			IOUtils.closeQuietly(in);
		}
	}

	@Override
	public boolean isAllowedHost(String host) {
		return hosts.contains(host);
	}

	@Override
	public String simpifyURL(RequestContext context) {
		Enumeration<String> params = context.request.getParameterNames();
		while (params.hasMoreElements()) {
			String param = context.request.getParameter(params.nextElement());
			if (param.startsWith("http://")) {
				return param;
			}
		}
		return null;
	}
	
	@Required
	public void setUrlMapper(URLMapper urlMapper) {
		this.urlMapper = urlMapper;
	}
	
	public URLMapper getUrlMapper() {
		return urlMapper;
	}
}
